<template>
  <view class="chat-container">
    <!-- 头部 -->
    <view class="chat-header uni-pa-8">
      <view class="title">
        <text class="bi bi-robot"></text> 墨枢物理Ai智能助手
      </view>
      <view class="header-right">
        <view class="status" :class="{ 'online': isConnected }">
          <text class="status-dot"></text>
          {{ isConnected ? '在线' : '连接中...' }}
        </view>
        <text class="bi bi-trash3" @tap="clearHistory"></text>
      </view>
    </view>

    <!-- 消息列表 -->
    <scroll-view 
      class="message-list" 
      scroll-y 
      :scroll-top="scrollTop"
      :scroll-with-animation="true"
      @scrolltolower="onScrollToLower"
      ref="messageList"
    >
      <!-- 默认欢迎消息 -->
      <view class="message ai uni-mt-5 uni-pa-4">
        <image class="avatar" :src="url('logoalpha', '', 'png')" mode="aspectFill"></image>
        <view class="message-content uni-pa-4">
          <view class="message-bubble">
            <text class="text">您好！我是墨枢智能助手，很高兴为您服务。请问有什么可以帮您？</text>
          </view>
          <view class="message-actions">
            <view class="action-btn" @tap="quickQuestion('什么是物理?')">
              <text class="bi bi-question-circle"></text> 什么是物理?
            </view>
            <view class="action-btn" @tap="quickQuestion('物理有哪些分支?')">
              <text class="bi bi-mask"></text> 物理有哪些分支?
            </view>
          </view>
        </view>
      </view>

      <!-- 消息记录 -->
      <view 
        v-for="(msg, index) in messages" 
        :key="index"
        :class="['message', msg.role === 'user' ? 'user' : 'ai', {'typing': msg.isTyping}]"
      >
        <image 
          class="avatar" 
          :src="msg.role === 'user' ? userAvatar : url('logoalpha', '', 'png')" 
          mode="aspectFill"
        ></image>
        <view class="message-content uni-pa-4">
          <view class="message-bubble">
            <text class="text" :class="{'typing-text': msg.isTyping}">{{ msg.displayContent }}</text>
            <text class="time">{{ formatTime(msg.time) }}</text>
            <view v-if="msg.role === 'assistant'" class="message-footer">
              <view class="action-buttons">
                <button type="warn" class="action-btn copy-btn" @tap="copyMessage(msg.content)">
                  <text class="bi bi-clipboard"></text> 复制
                </button>
                <button class="action-btn like" :class="{ 'active': msg.liked }" @tap="handleLike(index)">
                  <text class="bi bi-emoji-kiss-fill"></text>
                  <text class="count" v-if="msg.likeCount">{{ msg.likeCount }}</text>
                </button>
                <button class="action-btn dislike" :class="{ 'active': msg.disliked }" @tap="handleDislike(index)">
                  <text class="bi bi-emoji-dizzy-fill"></text>
                  <text class="count" v-if="msg.dislikeCount">{{ msg.dislikeCount }}</text>
                </button>
                <button class="action-btn favorite" :class="{ 'active': msg.favorited }" @tap="handleFavorite(index)">
                  <text class="bi bi-star-fill"></text>
                </button>
                <button class="action-btn delete" @tap="handleDelete(index)">
                  <text class="bi bi-trash3-fill"></text>
                </button>
              </view>
            </view>
          </view>
          <view v-if="msg.error" class="retry-section">
            <text class="error-msg">发送失败</text>
            <button class="retry-btn" @tap="retryMessage(index)">
              <text class="bi bi-arrow-clockwise"></text> 重试
            </button>
          </view>
        </view>
      </view>

      <!-- 加载动画 -->
      <view v-if="loading && !isStreaming" class="loading">
        <view class="dot"></view>
        <view class="dot"></view>
        <view class="dot"></view>
      </view>
    </scroll-view>

    <!-- 输入框 -->
    <view class="input-section uni-mx-4 ">
      <view class="d-flex justify-content-between align-items-center">
        <textarea
          v-model="inputMessage"
          class="w-100 h-100"
          :disabled="loading"
          placeholder="请输入您的问题..."
          :cursor-spacing="40"
          :show-confirm-bar="false"
          :auto-height="true"
          @confirm="sendMessage"
        />
        <view>  
          <button 
           style="background: var(--td-brand-color);"
            class="text-white uni-radius-lg"
            :disabled="!inputMessage.trim() || loading"
            @tap="sendMessage"
          >
            <text class="bi bi-send"></text>
          </button>
        </view>
      </view>
    </view>

    <!-- 添加表情动画容器 -->
    <view v-if="showEmojiAnimation" class="emoji-container">
      <text 
        v-for="(emoji, index) in activeEmojis" 
        :key="index" 
        class="floating-emoji"
        :style="{ 
          left: emoji.left + 'px',
          animationDelay: emoji.delay + 's',
          bottom: '-20px'
        }"
      >
        {{ emoji.text }}
      </text>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted, nextTick } from 'vue';
import { useUserStore } from '@/stores/userStore';

const url = $url;
const userStore = useUserStore();
const userAvatar = ref(userStore.userInfo.avatar);

const messages = ref([]);
const inputMessage = ref('');
const loading = ref(false);
const isConnected = ref(false);
const scrollTop = ref(0);
const messageList = ref(null);
const isStreaming = ref(false);

// 消息持久化
const STORAGE_KEY = 'ai_chat_messages';

// 加载历史消息
const loadHistoryMessages = () => {
  try {
    const history = uni.getStorageSync(STORAGE_KEY);
    if (history) {
      messages.value = JSON.parse(history);
    }
  } catch (error) {
    console.error('加载历史消息失败:', error);
  }
};

// 保存消息历史
const saveMessages = () => {
  try {
    uni.setStorageSync(STORAGE_KEY, JSON.stringify(messages.value));
  } catch (error) {
    console.error('保存消息失败:', error);
  }
};

// 清空历史记录
const clearHistory = () => {
  uni.showModal({
    title: '提示',
    content: '确定要清空聊天记录吗？',
    success: (res) => {
      if (res.confirm) {
        messages.value = [];
        uni.removeStorageSync(STORAGE_KEY);
        uni.showToast({
          title: '已清空聊天记录',
          icon: 'success'
        });
      }
    }
  });
};

// 重试消息
const retryMessage = async (index) => {
  const message = messages.value[index];
  if (!message || message.role !== 'user') {
    console.warn('无效的重试消息');
    return;
  }

  console.log('准备重试消息:', message);
  message.error = false;
  loading.value = true;

  try {
    await sendMessage(message.content, true);
    console.log('重试成功');
  } catch (error) {
    console.error('重试失败:', error);
    message.error = true;
  } finally {
    loading.value = false;
  }
};

// 快速提问
const quickQuestion = (question) => {
  inputMessage.value = question;
  sendMessage();
};

// 滚动到底部
const scrollToBottom = () => {
  nextTick(() => {
    const query = uni.createSelectorQuery();
    query.select('.message-list').boundingClientRect(data => {
      if (data) {
        scrollTop.value = data.height * 2; // 确保滚动到底部
      }
    }).exec();
  });
};

// 格式化时间
const formatTime = (time) => {
  const date = new Date(time);
  const hours = date.getHours().toString().padStart(2, '0');
  const minutes = date.getMinutes().toString().padStart(2, '0');
  return `${hours}:${minutes}`;
};

// 处理滚动到底部事件
const onScrollToLower = () => {
  // 可以在这里添加滚动到底部的具体逻辑
};

// 复制消息内容
const copyMessage = (content) => {
  uni.setClipboardData({
    data: content,
    success: () => {
      uni.showToast({
        title: '复制成功',
        icon: 'success'
      });
    }
  });
};

// 添加新的响应式变量
const showEmojiAnimation = ref(false);
const activeEmojis = ref([]);

// 修改表情动画实现
const showEmoji = () => {
  const emojis = ['❤️', '😍', '🥰', '💖', '💝', '💕', '💓', '💗', '💞', '😘', '🌹', '✨', '💫', '🌟', '⭐️', '🎉', '🎊'];
  const systemInfo = uni.getSystemInfoSync();
  const screenWidth = systemInfo.windowWidth;
  
  // 清空现有表情
  activeEmojis.value = [];
  
  // 创建更多表情（增加到12个）
  for (let i = 0; i < 12; i++) {
    activeEmojis.value.push({
      text: emojis[Math.floor(Math.random() * emojis.length)],
      left: Math.random() * screenWidth,
      delay: Math.random() * 0.8, // 增加延迟时间范围
      scale: 0.8 + Math.random() * 0.8 // 添加随机大小
    });
  }
  
  // 显示动画
  showEmojiAnimation.value = true;
  
  // 3.5秒后隐藏（稍微延长动画时间）
  setTimeout(() => {
    showEmojiAnimation.value = false;
  }, 3500);
};

// 修改点赞处理函数
const handleLike = (index) => {
  const msg = messages.value[index];
  if (msg.disliked) {
    msg.disliked = false;
    msg.dislikeCount = (msg.dislikeCount || 1) - 1;
  }
  msg.liked = !msg.liked;
  msg.likeCount = msg.liked ? (msg.likeCount || 0) + 1 : (msg.likeCount || 1) - 1;
  
  if (msg.liked) {
    showEmoji();
    // 添加震动反馈
    uni.vibrateShort({
      success: function () {
        console.log('震动成功');
      }
    });
  }
  saveMessages();
};

const handleDislike = (index) => {
  const msg = messages.value[index];
  if (msg.liked) {
    msg.liked = false;
    msg.likeCount = (msg.likeCount || 1) - 1;
  }
  msg.disliked = !msg.disliked;
  msg.dislikeCount = msg.disliked ? (msg.dislikeCount || 0) + 1 : (msg.dislikeCount || 1) - 1;
  saveMessages();
};

const handleFavorite = (index) => {
  const msg = messages.value[index];
  msg.favorited = !msg.favorited;
  saveMessages();
  
  uni.showToast({
    title: msg.favorited ? '已收藏' : '已取消收藏',
    icon: 'none'
  });
};

// 添加删除消息的处理函数
const handleDelete = (index) => {
  uni.showModal({
    title: '提示',
    content: '确定要删除这条消息吗？',
    success: (res) => {
      if (res.confirm) {
        messages.value.splice(index, 1);
        saveMessages();
        uni.showToast({
          title: '已删除',
          icon: 'success'
        });
      }
    }
  });
};

// 添加发送消息函数
const sendMessage = async (content = inputMessage.value, isRetry = false) => {
  const messageText = isRetry ? content : inputMessage.value.trim();
  
  if (!messageText) {
    uni.showToast({
      title: '请输入消息内容',
      icon: 'none'
    });
    return;
  }
  
  if (loading.value) {
    return;
  }

  const userMessage = {
    role: 'user',
    content: messageText,
    displayContent: messageText,
    time: new Date()
  };
  
  if (!isRetry) {
    messages.value.push(userMessage);
    inputMessage.value = '';
  }
  
  loading.value = true;
  isStreaming.value = true;
  await nextTick();
  scrollToBottom();

  try {
    const requestMessages = [
      {
        role: 'system',
        content: '你是一个专业的物理学助手，你叫墨小枢，可以回答各种物理相关的问题。你喜欢吃冰糖葫芦、椒盐味小鱼干'
      }
    ];

    if (messages.value.length > 0) {
      const historyMessages = messages.value.slice(-5).map(msg => ({
        role: msg.role,
        content: String(msg.content)
      }));
      requestMessages.push(...historyMessages);
    }

    requestMessages.push({
      role: 'user',
      content: String(messageText)
    });

    // 创建AI回复消息占位
    const aiMessage = {
      role: 'assistant',
      content: '正在思考中',
      displayContent: '正在思考中',
      time: new Date(),
      isTyping: true
    };
    messages.value.push(aiMessage);

    const response = await uni.request({
      url: 'https://api.deepseek.com/v1/chat/completions',
      method: 'POST',
      header: {
        'Content-Type': 'application/json',
        'Authorization': userStore.aiAuth
      },
      data: {
        model: 'deepseek-chat',
        messages: requestMessages,
        stream: false
      }
    });

    if (response.statusCode === 200 && response.data) {
      const responseData = response.data;
      if (responseData.choices && responseData.choices[0].message) {
        // 添加一个小延迟，让"正在思考"的动画效果更明显
        await new Promise(resolve => setTimeout(resolve, 500));
        aiMessage.content = responseData.choices[0].message.content;
        aiMessage.displayContent = responseData.choices[0].message.content;
        aiMessage.isTyping = false;
        scrollToBottom();
      }
    } else {
      throw new Error('API响应错误: ' + response.statusCode);
    }
  } catch (error) {
    console.error('发送消息失败:', error);
    userMessage.error = true;
    // 从消息列表中移除失败的 AI 消息
    const index = messages.value.indexOf(aiMessage);
    if (index > -1) {
      messages.value.splice(index, 1);
    }
    uni.showToast({
      title: '发送失败，请稍后重试',
      icon: 'none',
      duration: 2000
    });
  } finally {
    loading.value = false;
    isStreaming.value = false;
    await nextTick();
    scrollToBottom();
    saveMessages();
  }
};

onMounted(() => {
  isConnected.value = true;
  loadHistoryMessages();
});
</script>

<style lang="scss" scoped>
.chat-container {
  min-height: 90vh;
  background: url(https://epoch.jxksd.top/mo/images/dbg.png) no-repeat top
  center/cover;
  display: flex;
  flex-direction: column;
}

.chat-header {
  background: #fff;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);
  
  .title {
    font-size: 32rpx;
    font-weight: bold;
    color: var(--td-brand-color);
    
    .bi {
      margin-right: 10rpx;
    }
  }
  
  .header-right {
    display: flex;
    align-items: center;
    gap: 20rpx;
    
    .status {
      display: flex;
      align-items: center;
      gap: 6rpx;
      font-size: 24rpx;
      
      &.online .status-dot {
        background: #28a745;
      }
      
      .status-dot {
        width: 12rpx;
        height: 12rpx;
        border-radius: 50%;
        background: #666;
      }
    }
    
    .bi-trash3 {
      font-size: 32rpx;
      color: #666;
      &:active {
        opacity: 0.7;
      }
    }
  }
}

.message-list {
  flex: 1;
  padding: 20rpx;
  padding-bottom: 180rpx;
  overflow-y: auto;
  margin-bottom: env(safe-area-inset-bottom);
}

.message {
  display: flex;
  margin-bottom: 30rpx;
  padding: 0 20rpx;
  
  &.user {
    flex-direction: row-reverse;
    
    .message-content {
      margin-left: 0;
      margin-right: 20rpx;
      background: var(--td-brand-color);
      color: #fff;
      
      &::before {
        left: auto;
        right: -16rpx;
        border-left-color: var(--td-brand-color);
        border-right-color: transparent;
      }
      
      .time {
        color: rgba(255, 255, 255, 0.7);
      }
    }
  }
  
  &.typing {
    .message-bubble {
      .text {
        &.typing-text::after {
          content: '▋';
          display: inline-block;
          animation: blink 1s infinite;
          margin-left: 2px;
          font-weight: bold;
        }
      }
    }
  }
}

.avatar {
  width: 80rpx;
  height: 80rpx;
  border-radius: 50%;
  flex-shrink: 0;
 
}

.message-content {
  max-width: 70%;

  background: #fff;
  border-radius: 20rpx;
  position: relative;
  
  &::before {
    content: '';
    position: absolute;
    top: 20rpx;
    left: -16rpx;
    border: 8rpx solid transparent;
    border-right-color: #fff;
  }
  
  .message-bubble {
    position: relative;
    padding: 20rpx;
    border-radius: 16rpx;
    box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);
    transition: all 0.3s ease;
    
    .text {
      font-size: 28rpx;
      line-height: 1.6;
      word-break: break-all;
      white-space: pre-wrap;
      
      &.typing-text {
        &::after {
          content: '';
          display: inline-block;
          margin-left: 4px;
          animation: thinking 1.4s infinite;
        }
      }
    }
    
    .time {
      font-size: 24rpx;
      opacity: 0.7;
      margin-top: 10rpx;
      display: block;
      text-align: right;
    }
  }
}

.message-actions {
  display: flex;
  flex-wrap: wrap;
  gap: 10rpx;
  margin-top: 10rpx;
  
  .action-btn {
    font-size: 24rpx;

    background: rgba(0, 0, 0, 0.05);

    color: #666;
    
    .bi {
      margin-right: 4rpx;
    }
    
    &:active {
      opacity: 0.7;
    }
  }
}

.retry-section {
  display: flex;
  align-items: center;
  gap: 10rpx;
  margin-top: 10rpx;
  
  .error-msg {
    font-size: 24rpx;
    color: #dc3545;
  }
  
  .retry-btn {
    font-size: 24rpx;

    background: #dc3545;
    color: #fff;
    border-radius: 20rpx;
    
    .bi {
      margin-right: 4rpx;
    }
  }
}

.loading {
  display: flex;
  justify-content: center;
  gap: 10rpx;
 
  
  .dot {
    width: 12rpx;
    height: 12rpx;
    background: var(--td-brand-color);
    border-radius: 50%;
    animation: bounce 1s infinite;
    
    &:nth-child(2) {
      animation-delay: 0.2s;
    }
    
    &:nth-child(3) {
      animation-delay: 0.4s;
    }
  }
}

@keyframes bounce {
  0%, 100% {
    transform: translateY(0);
  }
  50% {
    transform: translateY(-10rpx);
  }
}

.input-section {
  background: linear-gradient(rgba(var(--td-brand-color-rgb), 0.7), rgba(var(--td-brand-color-rgb), 0.6)), 
              url("https://epoch.jxksd.top/mo/images/ib0.jpg") no-repeat center center/cover;
  backdrop-filter: blur(1px);
  padding: 20rpx 32rpx;
  border-top: 2rpx solid rgba(var(--td-brand-color-rgb), 0.1);
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  z-index: 100;
  padding-bottom: calc(20rpx + env(safe-area-inset-bottom));
  
  .d-flex {
    display: flex;
    align-items: flex-end;
    gap: 20rpx;
  }
  
  textarea {
    flex: 1;
    background: rgba(255, 255, 255, 0.9); 
    min-height: 80rpx;
    max-height: 160rpx;
    padding: 20rpx;
    border-radius: 12rpx;
    font-size: 28rpx;
    line-height: 1.5;
    width: calc(100% - 120rpx);
    backdrop-filter: blur(5px);
    border: 1px solid rgba(var(--td-brand-color-rgb), 0.1);
    
   
  }
  
  button {
    width: 80rpx !important;
    height: 80rpx;
    padding: 0;
    display: flex;
    align-items: center;
    justify-content: center;
    margin: 0;
    flex-shrink: 0;
  
    
    &:disabled {
      opacity: 0.5;
    }
    
    &:active {
      transform: scale(0.95);
    }
  }
}

.message-footer {
  margin-top: 16rpx;
  
  .action-buttons {
    display: flex;
    align-items: center;
    gap: 12rpx;
    flex-wrap: nowrap;
    justify-content: flex-end;
    
    .action-btn {
      background: #f8f8f8;
      padding: 8rpx 16rpx;
      font-size: 24rpx;
      display: flex;
      align-items: center;
      gap: 4rpx;
      color: #666;
      transition: all 0.3s ease;
      min-width: 60rpx;
      justify-content: center;
      
      &.copy-btn {
        background: var(--td-brand-color);
        color: #fff;
      }
      
      &.delete {
        color: #dc3545;
        &:active {
          background: rgba(220, 53, 69, 0.1);
        }
      }
      
      &.active {
        transform: scale(1.1);
      }
      
      &.like.active {
        color: #ff4b4b;
        background: rgba(255, 75, 75, 0.1);
      }
      
      &.dislike.active {
        color: #666;
        background: rgba(102, 102, 102, 0.1);
      }
      
      &.favorite.active {
        color: #ffb800;
        background: rgba(255, 184, 0, 0.1);
      }
      
      .count {
        font-size: 20rpx;
      }
      
      &:active {
        transform: scale(0.95);
      }
      
      .bi {
        font-size: 24rpx;
      }
    }
  }
}

.emoji-container {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  pointer-events: none;
  z-index: 9999;
}

.floating-emoji {
  position: fixed;
  font-size: 48rpx;
  animation: floatUp 2.5s ease-in-out forwards;
  opacity: 0;
  transform-origin: center;
  
  &::after {
    content: '';
    position: absolute;
    width: 100%;
    height: 100%;
    background: radial-gradient(circle, rgba(255,255,255,0.2) 0%, rgba(255,255,255,0) 70%);
    filter: blur(4px);
  }
}

@keyframes floatUp {
  0% {
    transform: translateY(0) scale(0.5) rotate(0deg);
    opacity: 0;
  }
  10% {
    opacity: 1;
  }
  50% {
    transform: translateY(-50vh) scale(1.2) rotate(180deg);
  }
  100% {
    transform: translateY(-100vh) scale(0.8) rotate(360deg);
    opacity: 0;
  }
}

@keyframes blink {
  0%, 100% { opacity: 1; }
  50% { opacity: 0; }
}

@keyframes thinking {
  0% { content: ''; }
  25% { content: '.'; }
  50% { content: '..'; }
  75% { content: '...'; }
  100% { content: ''; }
}
</style>